import logging
import os
import json
import pickle
from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, 
                             QGroupBox, QProgressBar, QMessageBox)
from PySide6.QtGui import QFont, QIcon
from PySide6.QtCore import Signal
from components.data_configurator import DataConfigurator
from utils.data_processor import DataProcessor
from utils.pack_reader import PackReader

from app_data import AppData

logger = logging.getLogger(__name__)


class DataProcessWidget(QWidget):

    prev_clicked = Signal()
    """5. 数据处理Tab：负责输出指标配置、数据读取、处理、结果提示"""
    def __init__(self, app_data: AppData, parent=None):
        super().__init__(parent)
        self.app_data = app_data
        self.OUTPUT_FILE = app_data.OUTPUT_FILE  # 输出指标配置文件
        self.init_ui()
        self.parent = parent

    def init_ui(self):
        """搭建数据处理UI"""
        layout = QVBoxLayout(self)

        # 1. 标题区域
        title = QLabel("数据处理与导出")
        title.setFont(QFont("Arial", 16, QFont.Bold))
        layout.addWidget(title)

        # 配置说明
        desc = QLabel("配置每个指标的筛选和数据处理方式")
        layout.addWidget(desc)

        # 2. 输出指标配置（自定义组件）
        self.output_configurator = DataConfigurator()
        self._load_output_config()  # 加载默认输出配置
        layout.addWidget(self.output_configurator)

        # 3. 数据处理区域
        process_group = QGroupBox("数据处理")
        process_layout = QHBoxLayout(process_group)

        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        process_layout.addWidget(self.progress_bar)

        # 开始处理按钮
        self.process_btn = QPushButton("开始处理数据")
        self.process_btn.clicked.connect(self.start_data_process)
        process_layout.addWidget(self.process_btn)

        layout.addWidget(process_group)

        # 4. 底部按钮（上一步）
        btn_layout = QHBoxLayout()
        self.prev_btn = QPushButton("上一步：工步配置")
        self.prev_btn.setIcon(QIcon.fromTheme("go-previous"))
        self.prev_btn.clicked.connect(self.on_prev_clicked)
        btn_layout.addWidget(self.prev_btn)
        btn_layout.addStretch()
        layout.addLayout(btn_layout)

    def _load_output_config(self):
        """加载输出指标配置（JSON）"""
        if os.path.exists(self.OUTPUT_FILE):
            with open(self.OUTPUT_FILE, 'r', encoding='utf-8') as f:
                output_config = json.load(f)
                self.output_configurator.init_from_config(output_config)
        else:
            QMessageBox.warning(self, "配置缺失", f"未找到输出指标配置文件：{self.OUTPUT_FILE}，将使用默认配置")

    def get_output_config(self):
        """获取输出指标配置"""
        return self.output_configurator.get_all_configs()

    def start_data_process(self):
        """开始数据处理：先读取文件，再筛选处理"""
        file_type = self.app_data.file_type
        sheet_name = self.parent.file_tab.sheet_name
        selected_files = self.app_data.selected_files
        bms_config = self.parent.bms_tab.get_bms_config()
        if not selected_files:
            QMessageBox.warning(self, "无文件", "请先在首页「文件选择」中添加待处理文件")
            return
        device_config = self.parent.device_tab.get_current_config()
        if not device_config:
            QMessageBox.warning(self, "设备配置为空！", "请先在第二页「设备配置」中配置数据列映射关系")
            return

        self.pack_reader = PackReader(
            selected_files=selected_files,
            device_config=device_config,
            bms_config=bms_config,
            sheet_name=sheet_name,
            file_type=file_type
        )
        self.pack_reader.except_signal.connect(self.show_error)
        self.pack_reader.progress.connect(self.progress_bar.setValue)
        self.pack_reader.file_name.connect(self.process_data)  # 读取完成后触发筛选
        self.pack_reader.start()

    def process_data(self, data):
        """数据筛选处理（读取完成后调用）"""
        df = pickle.loads(data)
        workstep_config = self.parent.workstep_tab.get_workstep_config()
        output_config = self.get_output_config()
        device_config = self.parent.device_tab.get_current_config()
        if not workstep_config:
            logger.info("工步设置为空")
        # 启动筛选线程
        self.data_processor = DataProcessor(
            df=df,
            device_config=device_config,
            ouput_indicats=output_config,
            small_cycle=workstep_config
        )
        self.data_processor.except_signal.connect(self.show_error)
        self.data_processor.progress.connect(self.progress_bar.setValue)
        self.data_processor.finished.connect(self.process_finished)
        self.data_processor.start()

    def process_finished(self):
        """数据处理完成提示"""
        self.progress_bar.setValue(100)
        QMessageBox.information(self, "处理完成", "数据处理已完成，可导出结果（后续完善导出逻辑）")

    def show_error(self, msg):
        """显示错误信息"""
        QMessageBox.critical(self, "处理错误", f"数据处理出错：{msg}")

    def on_prev_clicked(self):
        """上一步按钮点击事件"""
        # 由主窗口处理切换Tab
        self.prev_clicked.emit()